# -*-coding:utf-8-*-

import time
import re
import requests
from requests.utils import cookiejar_from_dict
import pathlib
from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor, as_completed
import img2pdf
from PIL import Image

catalogurl = 'https://www.mingrisoft.com/EBookAjax/getCatalogInfo.html'
rootdir = pathlib.Path(r"D:")
pattern_picbaseurl = re.compile(r'var root_path = "(\S+)";')
pattern_maxcount = re.compile(r'var count = maxCount = ([0-9]+);')
pattern_firstcpage = re.compile(r'var first_chapter_page = ([0-9]+);')
pattern_ebookid = re.compile(r'var ebook_id = "([0-9]+)";')
session = requests.Session()
session.headers = {"X-Requested-With": "XMLHttpRequest",
                   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                                 "Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.53"}
cookies = {"PHPSESSID": "t4o1h1v07atfolmsqt2ef83j67"}
session.cookies = cookiejar_from_dict(cookies)


# 获取书的基本信息
def get_book_info(ebookurl):
    text = session.get(url=ebookurl).text
    picbaseurl = pattern_picbaseurl.search(text).group(1)  # 此书每页图片的下载base_url
    maxcount = int(pattern_maxcount.search(text).group(1))  # 书的最后一页
    firstcpage = int(pattern_firstcpage.search(text).group(1))  # 书的第一章的第一页
    ebookid = pattern_ebookid.search(text).group(1)  # 电子书id
    return picbaseurl, maxcount, firstcpage, ebookid


# 下载每一页的图片
def download_worker(picbaseurl, firstcpage, ebookid, filedir, que):
    post = {"p": None, "ebook_id": ebookid}
    pic_url = None
    while True:
        try:
            page = que.get(block=False)
        except Empty:
            break
        if page < firstcpage:
            pic_url = f'{picbaseurl}{page}.jpg'
        else:
            post['p'] = page
            catalog = session.post(url=catalogurl, data=post).json()
            chapter, path_code = catalog['chapter'], catalog['path_code']
            pic_url = f'{picbaseurl}{chapter}/{page}{path_code}.jpg'
        pic_content = session.get(url=pic_url).content
        pic_savepath = filedir / (str(page) + '.jpg')
        pic_savepath.write_bytes(pic_content)
        print('第' + str(page) + '页下载完成\n', end='')


# 转换成pdf
def convert_pdf(filedir: pathlib.Path):
    pics = list(filedir.iterdir())
    pics.sort(key=lambda p: int(p.stem))
    pics = [str(p) for p in pics]  # 转成字符串路径列表, img2pdf只支持字符串路径
    for i in pics:
        img = Image.open(str(i))
        img.save(str(i), quality=65, optimize=True)
    a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297))
    layout = img2pdf.get_layout_fun(a4inpt)
    with open(str(filedir / '合并.pdf'), 'wb') as f:
        f.write(img2pdf.convert(pics, layout=layout))


def download_res():
    """
    // 获取资源文件名称和id
    var all = []
    ones = document.querySelectorAll('.one');
    for(let i=1;i<ones.length;i++){
    	all.push([ones[i].innerHTML.replace('  ','-')])
    }
    var ds = document.querySelectorAll('.first a');
    for(let i=0;i<ds.length;i++){
    	var click = ds[i].attributes['onclick'].value
    	var c = click.slice(click.indexOf('(')+1,click.length-1)
    	all[i].push(c);
    }
    all.forEach((item)=>{console.log(item[0],item[1])})
    """
    list_res = [('第1章-Java基础应用——源码', 395),
                ('第2章-图形与图表操作——源码', 396),
                ('第3章-文字操作与数据库——源码', 397),
                ('第4章-网络安全与多线程——源码', 398),
                ('第5章-Swing程序设计——源码', 399)]
    path = r"F:\python&java\java\Java精彩编程200例"
    for res_name, res_id in list_res:
        with session.get(url=f'https://test.mingrisoft.com/downloadfree/{res_id}.html', stream=True) as r:
            file_size = int(r.headers['content-length'])
            down_size = 0
            with open(path + '\\' + res_name + '.zip', 'wb') as f:
                for chunk in r.iter_content(1024 * 1024):
                    f.write(chunk)
                    down_size += len(chunk)
                    print('\r{}下载进度：{:.2%}'.format(f.name, down_size / file_size), end='', flush=True)


def main():
    ebookurl = 'https://www.mingrisoft.com/ebook/539.html'
    filedir = rootdir / str(int(time.time()))
    filedir.mkdir(parents=True)
    picbaseurl, maxcount, firstcpage, ebookid = get_book_info(ebookurl)
    que = Queue()
    for p in range(1, maxcount):
        que.put(p)
    print('--->本书开始下载')
    with ThreadPoolExecutor(4) as excutor:
        fs = [excutor.submit(download_worker, picbaseurl, firstcpage, ebookid, filedir, que) for _ in range(4)]
        # for f in as_completed(fs):
        #     f.result()
    print('--->本书下载完成')
    print('--->开始转换pdf')
    convert_pdf(filedir)
    print('--->转换pdf完成')


if __name__ == '__main__':
    main()
